package com.topscomm.mpm.script;

import com.topscomm.mpm.pojo.*;
import com.topscomm.mpm.service.impl.MpmProjectTeamTypeService;
import com.topscomm.pub.util.*;
import com.topscomm.tap.common.ParameterCache;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import org.springframework.transaction.annotation.Transactional;

import com.topscomm.basic.util.PrimaryKeyUtil;
import com.topscomm.cbo.pojo.CboApprovalNodeInsEntity;
import com.topscomm.cbo.pojo.CboDeptEntity;
import com.topscomm.cbo.pojo.CboOrgEntity;
import com.topscomm.cbo.pojo.CboUserEntity;
import com.topscomm.cbo.service.impl.CboDeptService;
import com.topscomm.cbo.service.impl.CboOrgService;
import com.topscomm.cbo.service.impl.CboUserService;
import com.topscomm.mpm.MpmScript;
import com.topscomm.mpm.service.impl.MpmProjectAppointmentService;
import com.topscomm.mpm.service.impl.MpmProjectService;
import com.topscomm.mpm.service.impl.MpmProjectTeamService;
import com.topscomm.tap.ITapService;
import com.topscomm.tap.TapEntity;
import com.topscomm.tap.common.DatacodeCache;
import com.topscomm.tap.common.FlowDatacodeCache;
import com.topscomm.tap.common.SessionUserBean;
import org.springframework.util.CollectionUtils;

public class MpmProjectToAppointmentScript extends MpmScript {

    /**
     * 任务立项后自动生成任命书
     *
     * @param service
     * @param entity
     * @throws Exception
     */
    @Transactional
    public void appointmentFromProject(ITapService service, TapEntity entity) throws Exception {
        DatacodeCache datacodeCache = new DatacodeCache();
        // 审批节点实例
        CboApprovalNodeInsEntity nodeins = (CboApprovalNodeInsEntity) entity;
        String sourceid = ConvertUtil.convertToString(nodeins.getSourceid());
        MpmProjectService mpmProjectService = (MpmProjectService) SpringUtil
            .getBean("mpmProjectService");
        MpmProjectAppointmentService mpmProjectAppointmentService = (MpmProjectAppointmentService) SpringUtil
            .getBean("mpmProjectAppointmentService");
        MpmProjectTeamService mpmProjectTeamService = (MpmProjectTeamService) SpringUtil
            .getBean("mpmProjectTeamService");
        MpmProjectTeamTypeService mpmProjectTeamTypeService = (MpmProjectTeamTypeService) SpringUtil
            .getBean("mpmProjectTeamTypeService");
        CboUserService cboUserService = (CboUserService) SpringUtil.getBean("cboUserService");
        CboDeptService cboDeptService = (CboDeptService) SpringUtil.getBean("cboDeptService");
        CboOrgService cboOrgService = (CboOrgService) SpringUtil.getBean("cboOrgService");
        // 获取项目信息
        MpmProjectEntity mpmProjectEntity = mpmProjectService.queryById(sourceid);
        String projectCode = mpmProjectEntity.getProjectcode();
        String projectName = mpmProjectEntity.getProjectname();
        String pmManagerCode = mpmProjectEntity.getProjectmanagercode();
        String pmManagerName = mpmProjectEntity.getProjectmanager();
        String sponsorCode = mpmProjectEntity.getSponsorcode();
        String sponsorName = mpmProjectEntity.getSponsor();
        String ownerCode = mpmProjectEntity.getOwnercode();
        String ownerName = mpmProjectEntity.getOwner();
        // 创建任命书单据
        MpmProjectAppointmentEntity mpmProjectAppointmentEntity = new MpmProjectAppointmentEntity();
        mpmProjectAppointmentEntity.setProjectname(projectName);
        mpmProjectAppointmentEntity.setProjectcode(projectCode);
        // 创建SessionUserBean
        cboUserService = (CboUserService) SpringUtil.getBean("cboUserService");
        cboDeptService = (CboDeptService) SpringUtil.getBean("cboDeptService");
        cboOrgService = (CboOrgService) SpringUtil.getBean("cboOrgService");
        StringBufferProxy whereSql = new StringBufferProxy();
        whereSql.appendLineSingle(" code = '{0}' ", mpmProjectEntity.getUsercode());
        List<CboUserEntity> cboUserEntities = cboUserService.queryByWhere(whereSql.toString());
        whereSql.clear();
        whereSql.appendLineSingle(" code = '{0}'", mpmProjectEntity.getDeptcode());
        List<CboDeptEntity> cboDeptEntities = cboDeptService.queryByWhere(whereSql.toString());
        whereSql.clear();
        whereSql.appendLineSingle(" code = '{0}'", mpmProjectEntity.getOrgcode());
        List<CboOrgEntity> cboOrgEntities = cboOrgService.queryByWhere(whereSql.toString());
        SessionUserBean sessionUserBean = new SessionUserBean();
        sessionUserBean.setUser(cboUserEntities.get(0));
        sessionUserBean.setDept(cboDeptEntities.get(0));
        sessionUserBean.setWorkDept(cboDeptEntities.get(0));
        sessionUserBean.setOrg(cboOrgEntities.get(0));
        sessionUserBean.setWorkOrg(cboOrgEntities.get(0));
        // 赋值id和单号
        long[] arrayId = PrimaryKeyUtil.GeneIDs(mpmProjectAppointmentEntity.getTableName(), 1);
        mpmProjectAppointmentEntity.setId(arrayId[0]);
        String docNo = String.valueOf(arrayId[0]);
        docNo = docNo.substring(0, 6) + docNo.substring(9);
        mpmProjectAppointmentEntity.setValue(MpmProjectAppointmentEntity.FieldDocno, docNo);
        // 生成任命书标题：项目名称+组任命，例：山西地电表记轮换项目组任命
        mpmProjectAppointmentEntity.setAppointmenttitle(projectName + "项目组任命");
        whereSql.clear();
        // 设置maintitle
        StringBufferProxy mainTitle = new StringBufferProxy();
        mainTitle.appendSingle("{0}{1}于{2}提交项目任命申请! ", mpmProjectEntity.getDeptname(),
            mpmProjectEntity.getUsername(), DateUtil.dateToString(new Date(), "yyyy-MM-dd"));
        // 设置业务字段
        mpmProjectAppointmentEntity.setSyspush("1");
        mpmProjectAppointmentEntity.setProjectname(projectName);
        mpmProjectAppointmentEntity.setProjectcode(projectCode);
        mpmProjectAppointmentEntity.setUsercode(mpmProjectEntity.getUsercode());
        mpmProjectAppointmentEntity.setUsername(mpmProjectEntity.getUsername());
        mpmProjectAppointmentEntity.setApplyusercode(mpmProjectEntity.getUsercode());
        mpmProjectAppointmentEntity.setApplyusername(mpmProjectEntity.getUsername());
        mpmProjectAppointmentEntity.setDeptcode(mpmProjectEntity.getDeptcode());
        mpmProjectAppointmentEntity.setOrgcode(mpmProjectEntity.getOrgcode());
        mpmProjectAppointmentEntity.setApplydate(new Date());
        mpmProjectAppointmentEntity.setDocdate(new Date());
        mpmProjectAppointmentEntity.setApplydeptcode(cboDeptEntities.get(0).getCode());
        mpmProjectAppointmentEntity.setApplydeptname(cboDeptEntities.get(0).getName());
        mpmProjectAppointmentEntity.setApplyorgcode(cboOrgEntities.get(0).getCode());
        mpmProjectAppointmentEntity.setApplyorgname(cboOrgEntities.get(0).getName());
        mpmProjectAppointmentEntity.setProjectmanager(mpmProjectEntity.getProjectmanager());
        mpmProjectAppointmentEntity.setProjectmanagercode(mpmProjectEntity.getProjectmanagercode());
        mpmProjectAppointmentEntity.setSponsor(mpmProjectEntity.getSponsor());
        mpmProjectAppointmentEntity.setSponsor(mpmProjectEntity.getSponsorcode());
        mpmProjectAppointmentEntity.setOwner(mpmProjectEntity.getOwner());
        mpmProjectAppointmentEntity.setOwnercode(mpmProjectEntity.getOwnercode());
        mpmProjectAppointmentEntity.setAppointmentdescription(
            mpmProjectAppointmentService.getAppointmentDescription(mpmProjectEntity));
        String mpmDefaultSigner = ParameterCache.getValue("MpmDefaultSigner");
        if (!StringUtil.isEmpty(mpmDefaultSigner)) {
            String[] split = mpmDefaultSigner.split(",");
            mpmProjectAppointmentEntity.setSignercode(StringUtil.isEmpty(split[0]) ? "" : split[0]);
            mpmProjectAppointmentEntity.setSignername(StringUtil.isEmpty(split[1]) ? "" : split[1]);
        }
        // 设置审批流程
        List<Map<String, Object>> flowidList = new ArrayList<>();
        FlowDatacodeCache flowDatacodeCache = new FlowDatacodeCache();
        flowidList = flowDatacodeCache.getApprovalFlowListMap("ApprovalFlow_MpmProjectAppointment",
            mpmProjectAppointmentEntity.getApplyusercode(), "sortcode");
        if (flowidList.size() > 0) {// 赋值审批流程id
            mpmProjectAppointmentEntity
                .setFlowid(ConvertUtil.convertToLong(flowidList.get(0).get("id")));
        } else {
            // 赋值默认异常处理流程
            mpmProjectAppointmentEntity.setFlowid('0');
        }
        // 插入任命书实体
        mpmProjectAppointmentService.insert(mpmProjectAppointmentEntity);
        // 插入对应任命书的项目组成员子行
        long appointmentid = mpmProjectAppointmentEntity.getId();
        List<MpmProjectTeamTypeEntity> mpmProjectTeamTypeDoList = mpmProjectTeamTypeService
            .queryByWhere(" projectcode = '" + projectCode + "'");
        long teamId = 0;
        if (!CollectionUtils.isEmpty(mpmProjectTeamTypeDoList)) {
            teamId = mpmProjectTeamTypeDoList.get(0).getId();
        }
        MpmProjectTeamEntity pmDo = insertTeam(appointmentid, pmManagerCode, pmManagerName, "项目领导组",
            "pm", projectCode, teamId);
        MpmProjectTeamEntity sponsorDo = insertTeam(appointmentid, sponsorCode, sponsorName,
            "项目领导组", "sponsor", projectCode, teamId);
        MpmProjectTeamEntity ownDo = insertTeam(appointmentid, ownerCode, ownerName, "项目领导组",
            "owner", projectCode, teamId);
        //提交任命书单据
        mpmProjectAppointmentService
            .executeSubmit(mpmProjectAppointmentEntity, mainTitle.toString(), sessionUserBean);

        // 根据模板生成任命书
        mpmProjectAppointmentService
            .generateAppointment(mpmProjectAppointmentEntity, mpmProjectEntity);
    }

    /**
     * @param
     * @param appointmentid
     * @param usercode
     * @param username
     * @param workgroup
     * @param projectrole
     * @return
     * @Title: insertTeam
     * @description:插入项目组成员
     * @author: lanjianwei
     * @date: 2021年1月16日下午5:32:57
     * @modify:
     */
    private MpmProjectTeamEntity insertTeam(long appointmentid,
        String usercode, String username, String workgroup, String projectrole, String projectcode,
        Long teamId) {
        MpmProjectTeamService mpmProjectTeamService = (MpmProjectTeamService) SpringUtil
            .getBean("mpmProjectTeamService");
        MpmProjectTeamEntity mpmProjectTeamEntity = new MpmProjectTeamEntity();
        mpmProjectTeamEntity.setProjectcode(projectcode);
        mpmProjectTeamEntity.setProjectrole(projectrole);
        mpmProjectTeamEntity.setWorkgroup(workgroup);
        mpmProjectTeamEntity.setUsercode(usercode);
        mpmProjectTeamEntity.setUsername(username);
        mpmProjectTeamEntity.setAppointmenttype("1");
        mpmProjectTeamEntity.setAppointmentid(appointmentid);
        mpmProjectTeamEntity.setAppointdate(new Date());
        mpmProjectTeamEntity.setState(1);
        mpmProjectTeamEntity.setTeamid(teamId);
        String mpm_leaderDuty = ParameterCache.getValue("Mpm_LeaderDuty");
        String[] split = mpm_leaderDuty.split("。");
        if ("pm".equals(projectrole)) {
            mpmProjectTeamEntity.setDuty(split[2]);
        } else if ("sponsor".equals(projectrole)) {
            mpmProjectTeamEntity.setDuty(split[0]);
        } else {
            mpmProjectTeamEntity.setDuty(split[1]);
        }
        return mpmProjectTeamService.insert(mpmProjectTeamEntity);
    }


}
